var xml2js = require('xml2js');
var cal = require('../libs/cal');
var config = require('../../config');
var request = require('request');
var User = require('../models/User');
var eventproxy = require('eventproxy');
var message = require('../libs/message');

exports.verify = function(req,res){
		//console.log(req.query);
		var _data= {};
		var token = TOKEN;
		var signature = req.query.signature;
		var timestamp = req.query.timestamp;
		var nonce = req.query.nonce;
		var echostr = req.query.echostr;
		
		var array = new Array(token,timestamp,nonce);
		array.sort();
		var str = array.toString().replace(/,/g,"");
		var sha1Code = crypto.createHash("sha1");
		var code = sha1Code.update(str,'utf-8').digest("hex");
		
	    //console.log(code)

		if(code ===signature){
			res.send(echostr)	
		}else{
			res.send("error")
		}	
}

exports.robot = function(req,res){
	//console.log("1")
	var buf='';
	req.setEncoding('utf8');
	req.on('data',function(chunk){
		buf +=chunk;	
	})	

	req.on('end',function(){
		xml2js.parseString(buf,function(err,json){
		if(err){
			err.status=400;
		}else{
			req.body=json;
		}
	})
	User.findOne({openid:req.body.xml.FromUserName[0]},function(err,$user){
		if(err){

		}else{
			if($user){

				message.answer(req.body.xml,function(err,answer){
					res.json(answer);
				})

			}else{
				var aurl = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token='+req.weixin.access_token+'&openid='+req.body.xml.FromUserName[0]+'&lang=zh_CN';
				request(aurl,function(err,aresp,abody){
					//console.log(abody);
					abody = JSON.parse(abody);
					var _user = new User();
					_user.openid = abody.openid;
					_user.nickname = abody.nickname;
					_user.sex = abody.sex;
					_user.language = abody.language;
					_user.city = abody.city;
					_user.province = abody.province;
					_user.country = abody.country;
					_user.headimgurl = abody.headimgurl;
					_user.subcribe_time = abody.subcribe_time;
					_user.subcribe = abody.subcribe;
					_user.uid = abody.unionid;
					_user.save(function(err,$$user){
						message.answer(req.body.xml,function(err,answer){
							res.json(answer);
						})
					})
				})
			}
		}
		
	})

	// //console.log(req.body);
	// var time = Math.round(new Date().getTime()/1000)
	// var msg = {
	// 		"toUserName" : req.body.xml.FromUserName[0],
	// 		"fromUserName" : req.body.xml.ToUserName[0],
	// 		"content":"我们的客服将尽快为您解答（来自 小拓）"
	// 	}

	// var output=""+"<xml>" + 
	// 		 "<ToUserName><![CDATA[" + msg.toUserName + "]]></ToUserName>" + 
	// 		 "<FromUserName><![CDATA[" + msg.fromUserName + "]]></FromUserName>" + 
	// 		 "<CreateTime>" + time + "</CreateTime>" + 
	// 		 "<MsgType><![CDATA[text]]></MsgType>" + 
	// 		 "<Content><![CDATA[" + msg.content + "]]></Content>" + 
			  
	// 	"</xml>";

	// res.send(output)
	})
		
}

exports.syncserver = function(req,res){
	var data ={}
	// //console.log(req.weixin)
	// //console.log(req.query.url)
	// data.ticket = req.weixin.jsapi_ticket;
	// data.noncestr = cal.createNonceStr();
	// data.ts = cal.createTimeStamp();
	// data.signatrue= cal.calcSignature(req.weixin.jsapi_ticket,data.noncestr,data.ts,req.query.url);
	// data.appid= config.appid;
	// //console.log(data)
	data = cal.sign(req.weixin.jsapi_ticket,req.query.url)
	data.appid = config.appid;
	res.json(data)
}

exports.code2token = function(req,res){
	var code = req.query.code;
	request('https://api.weixin.qq.com/sns/oauth2/access_token?appid='+config.appid+'&secret='+config.appsecret+'&code='+code+'&grant_type=authorization_code',function(err,resp,body){
	   	body = JSON.parse(body)
	   	//console.log(body,body.access_token)
	    var url = 'https://api.weixin.qq.com/sns/userinfo?access_token='+body.access_token+'&openid='+body.openid+'&lang=zh_CN';
	    request(url,function(err,aresp,abody){
	    	abody = JSON.parse(abody)
	    	console.log(abody)
	    	User.findOne({openid:body.openid},function(err,user){
	    		if(user){
	    			user.headimgurl = abody.headimgurl;
	    			user.uid = abody.unionid;
	    			user.save(function(err,$user){
	    				res.json($user);
	    			})
	    		}else{
	    			var _user = new User();
	    			_user.openid = abody.openid;
	    			_user.nickname = abody.nickname;
	    			_user.sex = abody.sex;
	    			_user.language = abody.language;
	    			_user.city = abody.city;
	    			_user.province = abody.province;
	    			_user.country = abody.country;
	    			_user.headimgurl = abody.headimgurl;
	    			_user.uid = abody.unionid;
	    			_user.save(function(err,$user){
	    				res.json($user)
	    			})
	    		}
	    	})
	    })
	    
	})
}




exports.getnowtoken = function (req,res){
		res.send(req.weixin.access_token)
}

exports.createMenu = function(req,res){
		var url =  'https://api.weixin.qq.com/cgi-bin/menu/create?access_token='+req.weixin.access_token;
		var menu ={
	     "button":[
	     {
	          "name":"客户服务",
	          "sub_button":[
	           {
	              "type":"view",
	              "name":"问卷调查",
	              "url":"https://sojump.com/m/10590348.aspx"
	           },
	          {    
	              "type":"click",
	              "name":"中奖查询",
	              "key":"CZ_PRIZE"
	           },
	          {    
	              "type":"click",
	              "name":"联系我们",
	              "key":"TG_CONTACT"
	           },
	           {
	              "type":"view",
	              "name":"固件更新",
	              "url":"http://mp.weixin.qq.com/s?__biz=MzA4NDk4MzA4NQ==&mid=2650995478&idx=2&sn=40edf506bc099dca576e116302e8fbb8&scene=4#wechat_redirect"
	           }]
	      },
	      {
	           "name":"精彩活动",
	           "sub_button":[
	           {    
	               "type":"view",
	               "name":"大篷车游全国",
	               "url":"http://i.eqxiu.com/s/KCDCCtXX"
	            },
	            {
	               "type":"click",
	               "name":"预约上车",
	               "key":"TG_MOVEUP"
	            },
	            {
	               "type":"view",
	               "name":"历史资讯",
	               "url":"http://mp.weixin.qq.com/mp/getmasssendmsg?__biz=MzA4NDk4MzA4NQ==#wechat_webview_type=1&wechat_redirect"
	            }]
	       },{
	           "name":"关于拓攻",
	           "sub_button":[
	           {    
	               "type":"view",
	               "name":"拓攻历程",
	               "url":"http://b.eqxiu.com/s/xGLM1ptH"
	            },
	            {    
	               "type":"view",
	               "name":"加入拓攻",
	               "url":"http://h.eqxiu.com/s/D07QDdVj"
	            },
	            {
	               "type":"view",
	               "name":"精彩视频",
	               "url":"http://i.youku.com/i/UMzAyODA4MzM0OA==?spm=a2hww.20023042.uerCenter.5~5!2~A.Oe0ozj"
	            },
	            {
	               "type":"click",
	               "name":"测试功能",
	               "key":"TG_TEST"
            	}]
	       }]
	 }

		request.post({url:url,json:menu},function(err,resp,body){
		//console.log(body)
})
}

exports.beginsave = function(req,res){
	var url = 'https://api.weixin.qq.com/cgi-bin/user/get?access_token='+req.weixin.access_token;
	request(url,function(err,resp,body){
		body = JSON.parse(body);
		var users = body.data.openid;
		var ep = new eventproxy();
		ep.after('get_user',body.count,function(users){
			if(body.count === users.length){
				res.json('ok')
			}else{
				res.json('fail')
			}
		})

		users.forEach(function(user,index){
			var aurl = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token='+req.weixin.access_token+'&openid='+user+'&lang=zh_CN';
			request(aurl,function(err,aresp,abody){
				//console.log(abody);
				abody = JSON.parse(abody);
				var _user = new User();
				_user.openid = abody.openid;
				_user.nickname = abody.nickname;
				_user.sex = abody.sex;
				_user.language = abody.language;
				_user.city = abody.city;
				_user.province = abody.province;
				_user.country = abody.country;
				_user.headimgurl = abody.headimgurl;
				_user.subcribe_time = abody.subcribe_time;
				_user.subcribe = abody.subcribe;
				_user.uid = abody.unionid;
				_user.save(function(err,$user){
					//console.log(index);
					ep.emit('get_user',$user.openid);
				})
			})

		})
	})
}